<?php defined('SYSPATH') or die('No direct access allowed.');

class Controller_Users extends Controller_Site {
	public function action_index()
	{
            $user_list = ORM::factory('users')->order_by('name')->find_all();
            $this->setVar('user_list', $user_list);
        }
        
        public function action_show()
	{
            $param=$this->request->param('id');
            $user = ORM::factory('users', $param);
            $this->content->set('user', $user);
        }
        
        public function action_edit()
	{
            $param=$this->request->param('id');
            $form = View::factory('users/form')->set('action', URL::site('users/edit/'.$param));
            $ckeditor = new CKEditor();
            $config = array("toolbar" =>
                array(
                    array(  'Bold', 
                            'Italic', 
                            '-', 
                            'NumberedList', 
                            'BulletedList', 
                            '-', 
                            'Link', 
                            'Unlink', 
                            '-', 
                            'Table' )
                )
            );

            $user = ORM::factory('users', $param);
            $form->set('user', $user);
            if($this->request->method() == 'POST' ) {
                try {
                    $this->processForm($user);
                    $this->setFlash('notice', 'Sikeresen módosítottad a profilod!');
                    $this->request->redirect('index.php/users');
                }
                catch (ORM_Validation_Exception $e) {
                    $form->set('errors', $e->errors('models'));
                }
            }
            $action = 'users/edit/'.$param;
            $form->set('action', $action);
            $form->set('ckeditor', $ckeditor);
            $form->set('config', $config);
            $this->content->set('form', $form);
    }
        
    protected function processForm($user){
        $user->description = $this->request->post('description');
        $user->room = $this->request->post('room');
        $user->telephone = $this->request->post('telephone');
        
        if(isset($_FILES['image'])){
            if(!empty($user->image)){ unlink(realpath(Upload::$default_directory).DIRECTORY_SEPARATOR.'users'.DIRECTORY_SEPARATOR.$user->image);}
                if($_FILES['image']['error'] === UPLOAD_ERR_OK){
                    move_uploaded_file($_FILES['image']['tmp_name'], realpath(Upload::$default_directory).DIRECTORY_SEPARATOR.'users'.DIRECTORY_SEPARATOR.$_FILES['image']['name']);
                    $user->image = $_FILES['image']['name'];
                }
        }
        $user->save();
    }
}